package com.bj58.data.emailreports.sends;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.bj58.data.emailreports.controllers.DataInfoController;
import com.bj58.data.emailreports.utils.DateUtil;
import com.bj58.data.emailreports.utils.MailUtil;
import com.bj58.data.emailreports.utils.SubmitSms;
import com.bj58.groupbuy.util.PathUtil;

public class DataInfoSend extends BaseSend{

	public void errorWarn(String title,String emailContent,String telContent){
		MailUtil.javaMailSend(title, emailContent, "huangliang@58.com;guoxue@58.com",null);
    	Map<String,String> telMap=new HashMap<String,String>();
    	telMap.put("13522482231",title+":"+telContent);
    	telMap.put("13811583416",title+":"+telContent);
    	SubmitSms.submitMsg(telMap);
	}
	
	public static void main(String[] args) {
		DataInfoSend sender = new DataInfoSend();
		DataInfoController  controller = new DataInfoController();
		List<String> failedList = new ArrayList<String>();
		String searchDate = "";

		try {
			searchDate = DateUtil.getStringDate(DateUtil.getDateBefore(new Date(), 1),"yyyy-MM-dd"); 
			if(null != args && args.length > 0){
				if(args.length > 1 || !args[0].contains("-")){
					System.out.println("par error");
					System.exit(0);
				}
				searchDate =args[0].trim();
			}
			System.out.println(searchDate);
				
			controller.initialData(searchDate);  //查数据
			String tempContent = controller.getTempContent(); //读模板
			String filepath = PathUtil.getWFNamespaceFolder()+"/emailtemp/dataInfoReceiver.txt";
			
			BufferedReader reader = new BufferedReader(new FileReader(filepath));
			String line=reader.readLine();
			while(!StringUtils.isBlank(line)){
				String info[] = line.split("\\s+");
				String city=info[0];
				String cates=info[2];
				String emailAddr=info[3].trim();
				try{
					controller.dataInfoReport(tempContent,emailAddr,city,cates,searchDate);
				}catch(Exception e ){
					e.printStackTrace();
					failedList.add(city+"--"+emailAddr);
				}
				line=reader.readLine();
			}
			
		} catch (Exception e) {	//查询过程出错了说明全部发送失败
			StringWriter w= new StringWriter();
			PrintWriter p = new PrintWriter(w);
			e.printStackTrace(p);
			p.close();
			System.err.println(w.toString());
			sender.errorWarn("代理商帖子日报 发送出错!~ " + searchDate, w.toString().replace("\n", "<br>"), e.getMessage());
		}finally{
			if(failedList.size() > 0){	//一部分发送失败
				System.out.println("发送失败的代理商如下:");
				StringBuffer str = new StringBuffer("发送失败的代理商如下:");
				for(String s:failedList){
					System.out.println(s);
					str.append(s+"<br>");
				}
				sender.errorWarn("代理商帖子日报 部分发送失败!~ " + searchDate, str.toString(), "");
			}
		}
	}
}
